<template>

  <div class='goods-reading-wrap' v-if='isFinish'>
    <el-form label-width="120px" :model='ruleForm' ref='ruleReading'>
      <div class='goods-reading'>
        <h4>商品属性信息</h4>
        <el-form-item label='商品名称'>
          <p>{{goodsName}}</p>
        </el-form-item>
        <el-form-item label='商品图片' prop='goodImg' required>
          <p class='mark'>上传图片的尺寸160px * 160px，格式png，jpeg，jpg，gif</p>
          <div class='goods-img'>
            <img :src="ruleForm.goodImg">
          </div>
          <div class='upload-btn' v-if="showTab != '1'">
            <el-upload :before-upload="beforeAvatarUpload" accept="image/*" :http-request="uploadSectionFile"
                       :show-file-list="false"
                       action="1" class="upload-demo">
              <el-button :disabled="false" size="mini" type="primary">上传</el-button>
            </el-upload>
            <el-form-item label-width='20px'>
              <el-button size="mini" type="danger" @click='deleteImg'>删除</el-button>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label='适用阶段' prop='fitStep' required>
          <el-radio-group v-model="ruleForm.fitStep" @change='selectFitStep' :disabled='showTab == "1"'>
            <el-radio v-for='(item, index) in applicableStage' :label="index" :key='index'>{{item.label}}</el-radio>
          </el-radio-group>
          <div class='fit-step-box' v-if='showBabyOrMum == 2'>
            <p class='mark'>请选择适合的宝妈状态，可多选</p>
            <el-checkbox-group v-model="ruleForm.mumStatus" size="mini" :disabled='showTab == "1"'>
              <el-checkbox :checked='item.ischeck == 1' @change='handleMumStatus($event, item.code, index)'
                           v-for='(item, index) in mumOption' :label="item.code" :key='index' border>{{item.label}}
              </el-checkbox>
            </el-checkbox-group>
            <el-row>
              <el-col :span='14' class='gravidity-weeks' v-if='gravidityWeeksOption.length != 0'>
                <p class='mark'><span>怀孕中</span>请选择适合的孕期周数</p>
                <el-checkbox-group v-model="ruleForm.gravidityWeeks" @change="handleCheckedWeekChange($event, 0)"
                                   :disabled='showTab == "1"'>
                  <el-checkbox v-for="(item, index) in gravidityWeeksOption" :label="item.code" :key="index"
                               :checked='item.ischeck == 1' @change='getIndex($event, 0, item.labelIndex)'>
                    {{item.label}}
                  </el-checkbox>
                </el-checkbox-group>
                <el-checkbox
                  :indeterminate="ruleForm.gravidityWeeks.length > 0 && ruleForm.gravidityWeeks.length < gravidityWeeksOption.length"
                  v-model="checkAll"
                  @change="handleCheckAllChange($event, 0)" :disabled='showTab == "1"'>
                  全选
                </el-checkbox>
                <p class='selected-weeks' v-if='selectGravidityWeeks.length > 0'>
                  已选：
                  <el-tag size="small" type="success" v-for='(item, index) in selectGravidityWeeks' :key='index'>
                    {{item}}
                  </el-tag>
                </p>
              </el-col>
              <el-col :span='14' class='gravidity-weeks baby-weeks' v-if='babyWeeksOption.length != 0'>
                <p class='mark'><span>已有宝宝</span>请选择适合的产后时间</p>
                <el-checkbox-group v-model="ruleForm.babyWeeks" @change="handleCheckedWeekChange($event, 1)"
                                   :disabled='showTab == "1"'>
                  <el-checkbox v-for="(item, index) in babyWeeksOption" :label="item.code" :key="index"
                               :checked='item.ischeck == 1' @change='getIndex($event, 1, item.labelIndex)'>
                    {{item.label}}
                  </el-checkbox>
                </el-checkbox-group>
                <el-checkbox
                  :indeterminate="ruleForm.babyWeeks.length > 0 && ruleForm.babyWeeks.length < babyWeeksOption.length"
                  v-model="hasBabyCheckAll"
                  @change="handleCheckAllChange($event, 1)" :disabled='showTab == "1"'>
                  全选
                </el-checkbox>
                <p class='selected-weeks' v-if='selectBabyWeeks.length > 0'>
                  已选：
                  <el-tag size="small" type="success" v-for='(item, index) in selectBabyWeeks' :key='index'>
                    {{item}}
                  </el-tag>
                </p>
              </el-col>
            </el-row>
          </div>
          <el-row v-if='showBabyOrMum == 1 && babyOldOption.length != 0'>
            <el-col :span='14' class='gravidity-weeks baby-weeks'>
              <p class='mark'>请选择适合的宝宝年龄，可多选</p>
              <el-checkbox-group v-model="ruleForm.babyOld" @change="handleCheckedWeekChange($event, 2)">
                <el-checkbox v-for="(item, index) in babyOldOption" :label="item.code" :key="index"
                             :checked='item.ischeck == 1' @change='getIndex($event, 2, item.labelIndex - 1)'
                             :disabled='showTab == "1"'>{{item.label}}
                </el-checkbox>
              </el-checkbox-group>
              <el-checkbox
                :indeterminate="ruleForm.babyOld.length > 0 && ruleForm.babyOld.length < babyOldOption.length"
                v-model="babyOldCheckAll"
                @change="handleCheckAllChange($event, 2)" :disabled='showTab == "1"'>
                全选
              </el-checkbox>
              <p class='selected-weeks' v-if='selectBabyOld.length > 0'>
                已选：
                <el-tag size="small" type="success" v-for='(item, index) in selectBabyOld' :key='index'>
                  {{item}}
                </el-tag>
              </p>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label='国产/进口' required>
          <el-radio-group v-model="ruleForm.domesticAndImportId" :disabled='showTab == "1"'>
            <el-radio v-for='(item, index) in labelOption' :label="item.id" :key='index'>{{item.label_value}}</el-radio>
          </el-radio-group>
          <el-button type='primary' size='mini' style='margin-left: 30px' @click='openDialoglabel'
                     :disabled='showTab == "1"'>选择更多标签
          </el-button>
        </el-form-item>
        <el-form-item size='mini' v-if='selectedLabel.length != 0'>
          <el-table :data="selectedLabel" style="width: 60%;" stripe size='mini' max-height='230px' border>
            <el-table-column label='序号' type="index" width='100' align='center'></el-table-column>
            <el-table-column prop="labelName" label="标签名" align='center'></el-table-column>
            <el-table-column prop="selectedText" label="标签值" align='center' :formatter='format'></el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <div class='goods-reading'>
        <h4>商品品牌知识</h4>
        <el-form-item label='品牌名称'>
          <p>{{brandName}}</p>
        </el-form-item>
        <el-form-item label-width='50px'>
          <p class='goods-reading-label'>品牌介绍</p>
          <template>
            <div class='editor-container' v-if='showTab != "1"'>
              <wangeditor :catchContent.sync="ruleForm.brandIntroduce" :wordscount.sync='wordsLen.brandIntroduceLen.len'
                          :maxLen='maxLen'></wangeditor>
              <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.brandIntroduce)'
                         style='margin-left: 15px'>预览
              </el-button>
            </div>
            <div class='editor-look' v-else>
              <div class='editor-look-nav'>
                <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.brandIntroduce)'
                           style='margin-left: 15px'>预览
                </el-button>
              </div>
              <div class='editor-look-content' v-html='ruleForm.brandIntroduce'></div>
            </div>
          </template>
        </el-form-item>
        <el-form-item label-width='50px'>
          <p class='goods-reading-label'>产品系列</p>
          <template>
            <div class='editor-container' v-if='showTab != "1"'>
              <wangeditor :catchContent.sync="ruleForm.brandSeries" :wordscount.sync='wordsLen.brandSeriesLen.len'
                          :maxLen='maxLen'></wangeditor>
              <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.brandSeries)'
                         style='margin-left: 15px'>预览
              </el-button>
            </div>
            <div class='editor-look' v-else>
              <div class='editor-look-nav'>
                <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.brandSeries)'
                           style='margin-left: 15px'>预览
                </el-button>
              </div>
              <div class='editor-look-content' v-html='ruleForm.brandSeries'></div>
            </div>
          </template>
        </el-form-item>
        <h4>商品卖点/优势</h4>
        <el-form-item label-width='50px'>
          <div class='editor-container' v-if='showTab != "1"'>
            <wangeditor :catchContent.sync="ruleForm.goodsAdvantage" :wordscount.sync='wordsLen.goodsAdvantageLen.len'
                        :maxLen='maxLen'></wangeditor>
            <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.goodsAdvantage)'
                       style='margin-left: 15px'>预览
            </el-button>
          </div>
          <div class='editor-look' v-else>
            <div class='editor-look-nav'>
              <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.goodsAdvantage)'
                         style='margin-left: 15px'>预览
              </el-button>
            </div>
            <div class='editor-look-content' v-html='ruleForm.goodsAdvantage'></div>
          </div>
        </el-form-item>
        <h4>商品销售技巧</h4>
        <el-form-item label-width='50px'>
          <div class='editor-container' v-if='showTab != "1"'>
            <wangeditor :catchContent.sync="ruleForm.goodsSalesSkills"
                        :wordscount.sync='wordsLen.goodsSalesSkillsLen.len' :maxLen='maxLen'></wangeditor>
            <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.goodsSalesSkills)'
                       style='margin-left: 15px'>预览
            </el-button>
          </div>
          <div class='editor-look' v-else>
            <div class='editor-look-nav'>
              <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.goodsSalesSkills)'
                         style='margin-left: 15px'>预览
              </el-button>
            </div>
            <div class='editor-look-content' v-html='ruleForm.goodsSalesSkills'></div>
          </div>
        </el-form-item>
        <h4>产品答疑</h4>
        <el-form-item label-width='50px'>
          <div class='editor-container' v-if='showTab != "1"'>
            <wangeditor :catchContent.sync="ruleForm.goodsQuestion" :wordscount.sync='wordsLen.goodsQuestionLen.len'
                        :maxLen='maxLen'></wangeditor>
            <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.goodsQuestion)'
                       style='margin-left: 15px'>预览
            </el-button>
          </div>
          <div class='editor-look' v-else>
            <div class='editor-look-nav'>
              <el-button type="info" plain size='mini' @click='previewBtn(ruleForm.goodsQuestion)'
                         style='margin-left: 15px'>预览
              </el-button>
            </div>
            <div class='editor-look-content' v-html='ruleForm.goodsQuestion'></div>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <!---------------------选择标签弹框------------------------->
    <el-dialog title="选择标签" :visible.sync="dialoglabelVisible" :closeOnClickModal='false' :closeOnPressEscape='false'
               :show-close='false'>
      <div class="serch search-label">
        <div>
          <el-input placeholder="输入标签、段位搜索" v-model="selectLabelData.name" size="small"
                    style='width: 300px'></el-input>
          <el-button type="primary" size="small" class="serchcha" @click="getLabelList">查询</el-button>
        </div>
        <el-button type="primary" size="small" class="serchcha" @click="addLabel">新增标签</el-button>
      </div>
      <el-table ref="singleTable" max-height="350" :data="labelList" highlight-current-row style="width: 100%" stripe>
        <el-table-column type="index" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column prop="paramName" label="请选择标签名称" width="260">
          <template slot-scope='scope'>
            <el-checkbox v-model="scope.row.checked" @change='selectMoreLabelName($event, scope.$index)'>
              {{scope.row.name}}
            </el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="labelValue" label="请选择标签值">
          <template slot-scope="scope">
            <el-checkbox-group v-model="scope.row.selectedList" @change='selectMoreLabel($event, scope.$index)'>
              <el-checkbox v-for="(item, index) in scope.row.labelValue" :label="item.id" :key="index"
                           @change='getLabelText($event, scope.$index, item.labelValue)'>{{item.labelValue}}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
        <el-table-column align="center" width='100'>
          <template slot-scope='scope'>
            <el-checkbox v-model="scope.row.checkAll" @change='moreLabelCheckAll($event, scope.$index)'>全选</el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <div class="pageblock pageinput">
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" :current-page="selectLabelData.pageNum"
                       :page-sizes="[5,10]" :page-size="selectLabelData.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
      <div slot="footer" class="dialog-footer goodsFooter">
        <el-button type="primary" @click="submitFormSpe()" size="small">确定添加</el-button>
        <el-button @click="cancelSpe" size="small">取 消</el-button>
      </div>
      <el-dialog width="40%" title="新增标签" :visible.sync="addLabelVisible" :show-close='false' :close-on-click-modal='false' :close-on-press-escape='false' append-to-body>
        <new-label @cancelAddLabel='cancelAddLabel' @getLabelList='getLabelList(selectLabelData.pageSize, 1)'
                   :isAdd.sync='isAdd'></new-label>
      </el-dialog>
    </el-dialog>
    <!-------------------预览弹框--------------------------------------->
    <el-dialog title="预览" :visible.sync="dialogPreviewVisible" width="375px" class='preview-dialog' :close-on-click-modal='false' :close-on-press-escape='false'>
      <div class='preview-container'>
        <div v-html='previewHtml'></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import wangeditor from '../../../../../components/wangeditor/index'
  import newLabel from './newLabel'
  import {mapState} from 'vuex'
  import util from '@/util'
  import {
    uploadFile,
    getFile,
    getApplicableStage,
    saveGoodsCommodityKnowledge,
    findGoodsLabelsListPage,
    getDomesticAndImport,
    selectGoodsCommodityKnowledge,
    updateGoodsCommodityKnowledge
  } from '@/api'

  export default {
    name: 'index',
    data () {
      return {
        hasData: true, // 无商品知识
        showTab: null, //编辑或者查看状态
        isFinish: false,
        selectedLabel: [], //添加的label
        isAdd: null,
        dialoglabelVisible: false, //标签弹框
        labelOption: [], // 国产进口
        operateType: null, //0-备孕中 1-已有宝宝 2-宝宝
        // checkAll: false,          //怀孕周数全选
        // hasBabyCheckAll: false,   //已有宝宝全选
        // babyOldCheckAll: false,   //宝宝年龄
        mumOption: [],       //宝妈状态列表
        babyWeeksOption: [], //已有宝宝时长
        babyOldOption: [],   //宝宝年龄
        gravidityWeeksOption: [],   //宝妈怀孕周数
        selectGravidityWeeks: [],   //怀孕周数已选
        selectBabyWeeks: false,     // 已有宝宝周数已选
        selectBabyOld: [],          //宝宝已选
        addLabelVisible: false, //添加标签弹框
        labelList: [], //标签列表
        total: 0, //标签总数
        dialogPreviewVisible: false, //富文本预览
        previewHtml: '', //预览富文本
        selectLabelData: {
          name: '', //标签查询关键字
          pageSize: 10,
          pageNum: 1,
        },
        applicableStage: {}, //适应阶段tree
        maxLen: 2000, //富文本最大限制
        wordsLen: {
          brandIntroduceLen: {
            len: 0,
            name: '品牌介绍'
          },
          brandSeriesLen: {
            len: 0,
            name: '产品系列'
          },
          goodsAdvantageLen: {
            len: 0,
            name: '商品卖点/优势'
          },
          goodsSalesSkillsLen: {
            len: 0,
            name: '商品销售技巧'
          },
          goodsQuestionLen: {
            len: 0,
            name: '产品答疑'
          },
        },
        ruleForm: {
          id: '',
          name: this.goodsName,
          brandName: this.brandName,
          goodImg: '',
          pregnancy: [], //备孕code
          mumStatus: [], //宝妈状态
          gravidityWeeks: [], //怀孕周数已选code
          babyWeeks: [],      //产后周数已选code
          babyOld: [],        //宝宝年龄已选code
          gravidityWeeksIndex: [],   //怀孕中已选索引
          babyWeeksIndex: [],        //宝妈已有宝宝已选索引
          babyOldIndex: [],          //宝宝年龄已选索引
          fitStep: 0,   //适应阶段
          labels: [],   //标签
          domesticAndImportId: '', //进口国产
          brandIntroduce: '',      //品牌介绍
          brandSeries: '',         //产品系列
          goodsAdvantage: '',      //商品卖点
          goodsSalesSkills: '',    //销售技巧
          goodsQuestion: '',       //商品答疑
        },
        goodsCompanyId: '',
        imgWith: 160,              //图片尺寸宽
        imgHeight: 160,            //图片尺寸高
        showBabyOrMum: null,   //0:不展示 1:展示宝宝  2:展示宝妈
        mumCode: 'fae139a58a2d408ebff4d97896825f79',       //宝妈
        hasBabyCode: '98308dc5bb90ce1f5c7c0da5d4186bab',   //已有宝宝
        pregnancyCode: 'e6c4c385763a70f17eba3f2342ea0895', //备孕中
        gravidityCode: 'eda0c8b69ebc1a3e8388fdecaf483902', //怀孕中
        babyCode: '7b7cb124d1a48f919a4dbce0b3997065',      //宝宝
        allPerson: 'c211f0ea07b3146e6cc990d712239803',     //全部人群
      }
    },
    components: {
      wangeditor,
      newLabel
    },
    props: ['brandName', 'goodsName', 'activeName2', 'brandId'],
    computed: {
      activeName: function () {
        return this.activeName2
      },
      hasBabyCheckAll: {
        // getter
        get: function () {
          return this.ruleForm.babyWeeks.length === this.babyWeeksOption.length
        },
        // setter
        set: function (newValue) {}
      },
      checkAll: {
        get: function () {
          return this.ruleForm.gravidityWeeks.length === this.gravidityWeeksOption.length
        },
        set: function (newValue) {}
      },
      babyOldCheckAll: {
        get: function () {
          return this.ruleForm.babyOld.length === this.babyOldOption.length
        },
        set: function (newValue) {}
      },
      ...mapState(['merchantId', 'power']),
    },
    watch: {
      //商品知识切换时请求详情接口
      // activeName (cur, old) {
      //   if (cur == 'third' && (this.showTab == '3' || this.showTab == '1') && !this.ruleForm.goodImg) {
      //     this.getDetail()
      //   }
      // },
    },
    mounted () {
      this.ruleForm.id = util.getQuery('goosId')
      this.showTab = util.getQuery('showTab')
      this.goodsCompanyId = util.getQuery('goodsCompanyId')
      //编辑、查看状态
      if (this.showTab == '3' || this.showTab == '1') {
        if (this.activeName == 'third') {
          this.getDetail()
        }
      } else {
        //新增
        this.isFinish = true
        this.getStage()
      }
      this.getDomesticandimport()
    },
    methods: {
      //配置权限
      setRole (key) {
        return util.selectTitle(this.power, key)
      },
      //父组件修改showTab
      setShowTab (val) {
        this.$set(this, 'showTab', val)
      },
      //删除图片
      deleteImg () {
        this.ruleForm.goodImg = ''
      },
      //获取详情
      getDetail () {
        let data = {
          id: this.ruleForm.id,
          shopId: this.merchantId,
          goodsCompanyId: this.goodsCompanyId
        }
        selectGoodsCommodityKnowledge(data).then((res) => {
          let datas = res.data
          if (res.code == 200) {
            this.applicableStage = datas.tree
            //没有商品知识数据
            if (!datas.goodshop && !datas.xLable && !datas.goodsKnowledge) {
              this.hasData = false
              let active = this.applicableStage[0]
              //宝妈
              if (active.code == this.mumCode) {
                this.mumOption = active.children
                this.showBabyOrMum = 2
              } else if (active.code == this.babyCode) {
                //宝宝
                this.babyOldOption = active.children
                this.showBabyOrMum = 1
              } else {
                //全部人群
                this.showBabyOrMum = 0
              }
              this.isFinish = true
              return
            }
            let arr = this.applicableStage
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].ischeck == 1) {
                this.$set(this.ruleForm, 'fitStep', i)
                //宝妈
                if (arr[i].code == this.mumCode) {
                  this.mumOption = arr[i].children
                  this.showBabyOrMum = 2
                  for (let j = 0; j < this.mumOption.length; j++) {
                    if (this.mumOption[j].ischeck == 1) {
                      if (this.mumOption[j].code == this.hasBabyCode) {
                        //已有宝宝
                        this.babyWeeksOption = this.mumOption[j].children
                        for (let x = 0; x < this.babyWeeksOption.length; x++) {
                          if (this.babyWeeksOption[x].ischeck == 1) {
                            this.ruleForm.babyWeeksIndex.push(+this.babyWeeksOption[x].labelIndex)
                          }
                        }
                        this.handleCheckedWeekChange(this.ruleForm.babyWeeks, 1)
                      } else if (this.mumOption[j].code == this.pregnancyCode) {
                        // 备孕中
                        this.ruleForm.pregnancy = new Array(this.mumOption[j].code)
                      } else if (this.mumOption[j].code == this.gravidityCode) {
                        //怀孕中
                        this.gravidityWeeksOption = this.mumOption[j].children
                        for (let x = 0; x < this.gravidityWeeksOption.length; x++) {
                          if (this.gravidityWeeksOption[x].ischeck == 1) {
                            this.ruleForm.gravidityWeeksIndex.push(+this.gravidityWeeksOption[x].labelIndex)
                          }
                        }
                        this.handleCheckedWeekChange(this.ruleForm.gravidityWeeks, 0)
                      }
                    }
                  }
                } else if (arr[i].code == this.babyCode) {
                  //宝宝
                  this.babyOldOption = arr[i].children
                  this.showBabyOrMum = 1
                  for (let x = 0; x < this.babyOldOption.length; x++) {
                    if (this.babyOldOption[x].ischeck == 1) {
                      this.ruleForm.babyOldIndex.push(+this.babyOldOption[x].labelIndex - 1)
                    }
                  }
                  this.handleCheckedWeekChange(this.ruleForm.babyOld, 2)
                } else {
                  //全部人群
                  this.showBabyOrMum = 0
                }
              }
            }
            this.ruleForm.goodImg = datas.goodshop
            this.ruleForm.brandIntroduce = datas.goodsKnowledge.brandIntroduce
            this.ruleForm.brandSeries = datas.goodsKnowledge.brandSeries
            this.ruleForm.goodsAdvantage = datas.goodsKnowledge.goodsAdvantage
            this.ruleForm.goodsQuestion = datas.goodsKnowledge.goodsQuestion
            this.ruleForm.goodsSalesSkills = datas.goodsKnowledge.goodsSalesSkills
            if (datas.xLable && datas.xLable.goodsLabelId) {
              this.ruleForm.domesticAndImportId = datas.xLable.goodsLabelId
            } else {
              this.ruleForm.domesticAndImportId = this.labelOption[1].id
            }
            let lableArr = datas.moreLable
            let index = 0
            for (let key in lableArr) {
              this.selectedLabel.push({
                id: '',
                labelName: '',
                selectedText: [],
                selectedList: []
              })
              for (let i = 0; i < lableArr[key].length; i++) {
                this.selectedLabel[index].id = lableArr[key][i].labelId,
                  this.selectedLabel[index].labelName = lableArr[key][i].name,
                  this.selectedLabel[index].selectedList.push(lableArr[key][i].goodsLabelId)
                this.selectedLabel[index].selectedText.push(lableArr[key][i].label_value)
              }
              index += 1
            }
            this.isFinish = true
          } else {
            this.isFinish = true
            this.$message.error(res.msg)
          }

        })
      },
      //保存数据
      saveKnowledge (id) {
        //用户只修改了商品基础信息
        if (this.showTab == '3' && !this.ruleForm.goodImg) {
          this.$message.success('修改成功')
           util.routerTo(
                        "/operate-management/goods-management/goods-goodslist"
                      );
          return false
        }
        let data = {
          id: id,
          shopId: this.merchantId,
          goodImg: this.ruleForm.goodImg,
          brandIntroduce: this.ruleForm.brandIntroduce, //品牌介绍
          brandSeries: this.ruleForm.brandSeries, //产品系列
          goodsAdvantage: this.ruleForm.goodsAdvantage, //商品卖点
          goodsSalesSkills: this.ruleForm.goodsSalesSkills, //销售技巧
          goodsQuestion: this.ruleForm.goodsQuestion, //商品答疑
          labelValueList: [], //适应阶段
          domesticAndImportId: this.ruleForm.domesticAndImportId
        }
        if (this.showBabyOrMum == 1) {
          //宝宝
          data.labelValueList = this.ruleForm.babyOld
        } else if (this.showBabyOrMum == 2) {
          //宝妈
          data.labelValueList = this.ruleForm.pregnancy.concat(this.ruleForm.gravidityWeeks, this.ruleForm.babyWeeks)
        } else {
          //  全部人群
          data.labelValueList = new Array(this.allPerson)
        }
        for (let i = 0; i < this.selectedLabel.length; i++) {
          data.labelValueList = data.labelValueList.concat(this.selectedLabel[i].selectedList)
        }
        if (this.showTab == 3 && this.hasData) {
          this.$nextTick(() => {
            data.labelValueList.push(this.brandId)
            data.goodsCompanyId = this.goodsCompanyId
            updateGoodsCommodityKnowledge(data).then((res) => {
              if (res.code == 200) {
                this.$message.success('修改成功')
                 util.routerTo(
                        "/operate-management/goods-management/goods-goodslist"
                      );
              }
            })
          })
        } else {
          if (this.showTab == '3') {
            data.id = this.goodsCompanyId
          }
          this.$nextTick(() => {
            saveGoodsCommodityKnowledge(data).then((res) => {
              if (res.code == 200) {
                this.$message.success('保存成功')
                 util.routerTo(
                        "/operate-management/goods-management/goods-goodslist"
                      );
              }
            })
          })
        }
      },
      //适用阶段选择
      selectFitStep (val) {
        let active = this.applicableStage[val]
        //宝妈
        if (active.code == this.mumCode) {
          this.mumOption = active.children
          this.clearChecked(this.mumOption)
          this.showBabyOrMum = 2
          this.babyOldOption = []
          this.ruleForm.babyOld = []
          this.selectBabyOld = []
          this.ruleForm.babyOldIndex = []
          // this.babyOldCheckAll = false //宝宝年龄
        } else if (active.code == this.babyCode) {
          //宝宝
          this.babyOldOption = active.children
          this.showBabyOrMum = 1
          this.mumOption = []
          this.ruleForm.mumStatus = []
          this.ruleForm.gravidityWeeks = []
          this.ruleForm.pregnancy = []
          this.ruleForm.babyWeeks = []
          this.gravidityWeeksOption = []
          this.babyWeeksOption = []
          this.selectGravidityWeeks = []
          this.selectBabyWeeks = []
          this.ruleForm.gravidityWeeksIndex = []
          this.ruleForm.babyWeeksIndex = []
          // this.checkAll = false
          // this.hasBabyCheckAll = false
        } else {
          //全部人群
          this.showBabyOrMum = 0
          this.mumOption = []
          this.ruleForm.mumStatus = []
          // this.$set(this.ruleForm, 'gravidityWeeks', [])
          this.ruleForm.gravidityWeeks = []
          this.ruleForm.pregnancy = []
          this.ruleForm.babyWeeks = []
          this.babyOldOption = []
          this.ruleForm.babyOld = []
          this.gravidityWeeksOption = []
          this.babyWeeksOption = []
          this.selectGravidityWeeks = []
          this.selectBabyWeeks = []
          this.selectBabyOld = []
          this.ruleForm.gravidityWeeksIndex = []
          this.ruleForm.babyWeeksIndex = []
          this.ruleForm.babyOldIndex = []
          // this.babyOldCheckAll = false //宝宝年龄
          // this.checkAll = false
          // this.hasBabyCheckAll = false
        }
      },
      //清空数据
      clearChecked (arr) {
        for (let i = 0; i < arr.length; i++) {
          arr[i].ischeck = 0
          if (arr[i].children.length > 0) {
            this.clearChecked(arr[i].children)
          }
        }
      },
      //怀孕周数全选
      handleCheckAllChange (val, type) {
        switch (type) {
          //怀孕中
          case 0:
            if (val) {
              let codeArr = []
              let arr = []
              for (let i = 0; i < this.gravidityWeeksOption.length; i++) {
                arr.push(+this.gravidityWeeksOption[i].labelIndex)
                codeArr.push(this.gravidityWeeksOption[i].code)
              }
              this.ruleForm.gravidityWeeks = codeArr
              this.ruleForm.gravidityWeeksIndex = arr
              this.selectGravidityWeeks = ['1-40周']
            } else {
              this.ruleForm.gravidityWeeks = []
              this.ruleForm.gravidityWeeksIndex = []
              this.selectGravidityWeeks = []
            }
            break
          //已有宝宝
          case 1:
            if (val) {
              let codeArr2 = []
              let arr2 = []
              for (let i = 0; i < this.babyWeeksOption.length; i++) {
                arr2.push(+this.babyWeeksOption[i].labelIndex)
                codeArr2.push(this.babyWeeksOption[i].code)
              }
              this.ruleForm.babyWeeks = codeArr2
              this.ruleForm.babyWeeksIndex = arr2
              this.selectBabyWeeks = ['0-3年以上']
            } else {
              this.ruleForm.babyWeeks = []
              this.ruleForm.babyWeeksIndex = []
              this.selectBabyWeeks = []
            }
            break
          //宝宝年龄
          case 2:
            if (val) {
              let codeArr3 = []
              let arr3 = []
              for (let i = 0; i < this.babyOldOption.length; i++) {
                arr3.push(+this.babyOldOption[i].labelIndex - 1)
                codeArr3.push(this.babyOldOption[i].code)
              }
              this.ruleForm.babyOld = codeArr3
              this.ruleForm.babyOldIndex = arr3
              this.selectBabyOld = ['0-3岁以上']
            } else {
              this.ruleForm.babyOld = []
              this.ruleForm.babyOldIndex = []
              this.selectBabyOld = []
            }
            break
        }
      },
      //宝妈状态选择
      handleMumStatus (value, code, index) {
        if (value) {
          //已有宝宝
          if (code == this.hasBabyCode) {
            this.babyWeeksOption = this.mumOption[index].children
            this.clearChecked(this.babyWeeksOption)
          } else if (code == this.pregnancyCode) {
            // 备孕中
            this.ruleForm.pregnancy = new Array(code)
          } else if (code == this.gravidityCode) {
            //怀孕中
            this.gravidityWeeksOption = this.mumOption[index].children
            this.clearChecked(this.gravidityWeeksOption)
          }
        } else {
          //已有宝宝
          if (code == this.hasBabyCode) {
            this.babyWeeksOption = []
            this.ruleForm.babyWeeks = []
            this.ruleForm.pregnancy = []
            this.ruleForm.babyWeeksIndex = []
            this.selectBabyWeeks = []
            // this.hasBabyCheckAll = false //已有宝宝全选
          } else if (code == this.pregnancyCode) {
            // 备孕中
            this.ruleForm.pregnancy = []
          } else if (code == this.gravidityCode) {
            //怀孕中
            this.gravidityWeeksOption = []
            this.ruleForm.gravidityWeeks = []
            this.ruleForm.gravidityWeeksIndex = []
            this.selectGravidityWeeks = []
            this.ruleForm.pregnancy = []
            // this.checkAll = false
          }
        }
      },
      //多选勾选
      getIndex (val, type, index) {
        switch (type) {
          //怀孕中
          case 0:
            if (val) {
              this.ruleForm.gravidityWeeksIndex.push(+index)
            } else {
              this.ruleForm.gravidityWeeksIndex.splice(this.ruleForm.gravidityWeeksIndex.indexOf(+index), 1)
            }
            break
          //已有宝宝
          case 1:
            if (val) {
              this.ruleForm.babyWeeksIndex.push(+index)
            } else {
              this.ruleForm.babyWeeksIndex.splice(this.ruleForm.babyWeeksIndex.indexOf(+index), 1)
            }
            break
          //宝宝年龄
          case 2:
            if (val) {
              this.ruleForm.babyOldIndex.push(+index)
            } else {
              this.ruleForm.babyOldIndex.splice(this.ruleForm.babyOldIndex.indexOf(+index), 1)
            }
            break
        }
      },
      //选择怀孕周数
      handleCheckedWeekChange (value, type) {
        this.operateType = type
        switch (type) {
          //怀孕中
          case 0:
            let checkedCount = value.length
            // this.checkAll = checkedCount === this.ruleForm.gravidityWeeksIndex.length
            this.ruleForm.gravidityWeeksIndex.sort((a, b) => a - b)
            this.selectGravidityWeeks = this.weeksSort(this.ruleForm.gravidityWeeksIndex)
            break
          //已有宝宝
          case 1:
            let checkedCount2 = value.length
            // this.hasBabyCheckAll = checkedCount2 === this.ruleForm.babyWeeksIndex.length
            this.ruleForm.babyWeeksIndex.sort((a, b) => a - b)
            this.selectBabyWeeks = this.weeksSort(this.ruleForm.babyWeeksIndex)
            break
          //宝宝年龄
          case 2:
            let checkedCount3 = value.length
            // this.babyOldCheckAll = checkedCount3 === this.ruleForm.babyOldIndex.length
            this.ruleForm.babyOldIndex.sort((a, b) => a - b)
            this.selectBabyOld = this.weeksSort(this.ruleForm.babyOldIndex)
            break
        }
      },
      //选择标签名
      selectMoreLabelName (val, index) {
        if (!val) {
          this.$set(this.labelList[index], 'selectedList', [])
          this.$set(this.labelList[index], 'checkAll', false)
        }
      },
      //选择标签值
      selectMoreLabel (val, index) {
        let len = this.labelList[index].labelValue.length
        if (val.length > 0) {
          this.$set(this.labelList[index], 'checked', true)
          if (val.length == len) {
            this.$set(this.labelList[index], 'checkAll', true)
          } else {
            this.$set(this.labelList[index], 'checkAll', false)
          }
        } else {
          this.$set(this.labelList[index], 'checkAll', false)
        }
      },
      //标签值全选
      moreLabelCheckAll (val, index) {
        let arr = this.labelList[index].labelValue
        let newArr = []
        let newArr2 = []
        if (val) {
          for (let i = 0; i < arr.length; i++) {
            newArr.push(arr[i].id)
            newArr2.push(arr[i].labelValue)
          }
          this.$nextTick(() => {
            this.$set(this.labelList[index], 'checked', true)
            this.$set(this.labelList[index], 'selectedList', newArr)
            this.$set(this.labelList[index], 'selectedText', newArr2)
          })
        } else {
          this.$set(this.labelList[index], 'checked', false)
          this.$set(this.labelList[index], 'selectedList', [])
          this.$set(this.labelList[index], 'selectedText', [])
        }
      },
      //选择标签获取文本
      getLabelText (val, index, name) {
        let arr = this.labelList[index].selectedText
        if (val) {
          arr.push(name)
        } else {
          arr.splice(arr.indexOf(name), 1)
        }
      },
      //获取适应阶段数据
      getStage () {
        getApplicableStage({
          // "labelId":"8249be80ca2b466ea6e3672d2f584e98"
        }).then((res) => {
          if (res.code == 200) {
            this.applicableStage = res.data
            let active = this.applicableStage[0]
            //宝妈
            if (active.code == this.mumCode) {
              this.mumOption = active.children
              this.showBabyOrMum = 2
            } else if (active.code == this.babyCode) {
              //宝宝
              this.babyOldOption = active.children
              this.showBabyOrMum = 1
            } else {
              //全部人群
              this.showBabyOrMum = 0
            }
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      //添加更多标签
      submitFormSpe () {
        let arr = this.labelList
        this.selectedLabel = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].checked == true) {
            if (arr[i].selectedText.length == 0) {
              this.$message.error('每条标签至少选择一个标签值')
              return
            } else {
              this.selectedLabel.push({
                id: arr[i].glId,
                labelName: arr[i].name,
                selectedText: arr[i].selectedText,
                selectedList: arr[i].selectedList
              })
            }
          }
        }
        this.dialoglabelVisible = false
      },
      // 取消
      cancelSpe () {
        this.dialoglabelVisible = false
      },
      //取消新增标签
      cancelAddLabel () {
        this.addLabelVisible = false
        this.isAdd = null
      },
      //新增标签
      addLabel () {
        this.isAdd = 1
        this.addLabelVisible = true
      },
      //预览弹框
      previewBtn (html) {
        this.previewHtml = `<div class='rich-text-details'>${html}</div>`
        this.dialogPreviewVisible = true
      },
      //获取标签类型
      getLabelList (pageSize, pageNum) {
        let data = {
          shopId: this.merchantId,
          name: this.selectLabelData.name,
          pageNum: pageNum,
          pageSize: pageSize
        }
        findGoodsLabelsListPage(data).then(res => {
          this.dialoglabelVisible = true
          let datas = res.data.list
          if (res.code == 200) {
            if (this.selectedLabel.length == 0) {
              for (let i = 0; i < datas.length; i++) {
                datas[i].checked = false
                datas[i].selectedList = []
                datas[i].checkAll = false
                datas[i].selectedText = []
              }
            } else {
              let arr2 = this.selectedLabel
              for (let i = 0; i < datas.length; i++) {
                datas[i].checked = false
                datas[i].selectedList = []
                datas[i].selectedText = []
                for (let j = 0; j < arr2.length; j++) {
                  if (arr2[j].id == datas[i].glId) {
                    datas[i].selectedText = arr2[j].selectedText
                    datas[i].selectedList = arr2[j].selectedList
                    datas[i].checked = true
                    if (arr2[j].selectedList.length == datas[i].labelValue.length) {
                      datas[i].checkAll = true
                    } else {
                      datas[i].checkAll = false
                    }
                  }
                }
              }
            }
            this.$nextTick(() => {
              this.labelList = datas
              this.total = res.data.pageTotal
              this.dialoglabelVisible = true
            })
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      //国产&进口
      getDomesticandimport () {
        getDomesticAndImport().then((res) => {
          if (res.code == 200) {
            this.labelOption = res.data
            if (this.labelOption.length > 1) {
              this.ruleForm.domesticAndImportId = res.data[1].id
            }
          }
        })
      },
      //选择标签弹框
      openDialoglabel () {
        this.getLabelList(this.selectLabelData.pageSize, 1)
      },
      //上传
      uploadSectionFile (param) {
        var fileObj = param.file
        var data = new FormData()
        data.append('projectName', fileObj.name)
        data.append('file', fileObj)
        uploadFile(data).then(res => {
          if (res.code == 200) {
            let a = `${getFile}?id=${res.data.id}`
            this.$set(this.ruleForm, 'goodImg', a)
          } else {
            this.tipsBox(res.msg, 'error')
          }
        })
      },
      //图片大小格式
      beforeAvatarUpload (file) {
        let that = this
        let width, height, isSize
        const isJPG =
          file.type === 'image/png' ||
          file.type === 'image/jpg' ||
          file.type === 'image/jpeg' ||
          file.type === 'image/gif'

        if (!isJPG) {
          this.$message.error('上传图片格式错误!')
          return false
        }

        isSize = new Promise(function (resolve, reject) {
          width = that.imgWith
          height = that.imgHeight

          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = img.width == width && img.height == height
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file)
        }).then(() => {
          return true
        }, () => {
          this.$message.error(`上传的图片必须是${width}px * ${height}px`)
          return Promise.reject()
        })
        return isJPG && isSize
      },
      //父组件中保存时校验必填项
      validKnoeledge () {
        if (!this.ruleForm.goodImg) {
          return '请上传商品图片'
        }
        if (this.showBabyOrMum == 1 && this.ruleForm.babyOld.length == 0) {
          //宝宝
          return '请选择适应阶段'
        }
        if (this.showBabyOrMum == 2) {
          //宝妈
          let labelValueList = this.ruleForm.pregnancy.concat(this.ruleForm.gravidityWeeks, this.ruleForm.babyWeeks)
          if (labelValueList.length == 0) {
            return '请选择适应阶段'
          }
        }
        // //富文本字数
        // for (let key in this.wordsLen) {
        //   if (this.wordsLen[key].len > this.maxLen) {
        //     return this.wordsLen[key].name + '文字内容超过2000个字'
        //   }
        // }
        return 'true'
      },
      //排序处理
      weeksSort (arr) {
        var result = []

        arr.forEach(function (v, i) {
          var temp = result[result.length - 1]
          if (!i) {
            result.push([v])
          } else if (v - temp[temp.length - 1] == 1) {
            temp.push(v)
          } else {
            result.push([v])
          }
        })
        if (this.operateType == 0) {
          return result.map(function (v) {
            if (v.length == 1) {
              return v + '周'
            } else {
              return (v[0] + '-' + v[v.length - 1]) + '周'
            }
          })
        } else if (this.operateType == 1) {
          let that = this
          return result.map(function (v, index) {
            if (v.length == 1) {
              return that.babyWeeksOption[v].label
            } else {
              let v0 = +v[0]
              let vLen = +v[v.length - 1]
              let new0, newLen
              if (v0 == 1) {
                new0 = '6周'
              } else if (v0 < 13) {
                new0 = v0
              } else if (v0 == 13) {
                new0 = '18'
              } else if (v0 == 14) {
                new0 = '2'
              }
              if (vLen < 12) {
                newLen = (vLen + 1) + '个月'
              } else if (vLen == 12) {
                newLen = '18个月'
              } else if (vLen == 13) {
                newLen = '24个月'
              } else if (vLen == 14) {
                newLen = '3年'
              } else if (vLen == 15) {
                newLen = '3年以上'
              }
              if (vLen > 13 && v0 < 14 && v0 != 1) {
                return `${new0}个月-${newLen}`
              } else {
                return `${new0}-${newLen}`
              }
            }
          })
        } else {
          let that = this
          return result.map(function (v, index) {
            if (v.length == 1) {
              return that.babyOldOption[v].label
            } else {
              let v0 = +v[0]
              let vLen = +v[v.length - 1]
              let new0, newLen
              if (v0 == 1) {
                new0 = '28天'
              } else if (v0 < 13) {
                new0 = v0
              } else if (v0 == 13) {
                new0 = '18'
              } else if (v0 == 14) {
                new0 = '2'
              }
              if (vLen < 12) {
                newLen = (vLen + 1) + '个月'
              } else if (vLen == 12) {
                newLen = '18个月'
              } else if (vLen == 13) {
                newLen = '24个月'
              } else if (vLen == 14) {
                newLen = '3岁'
              } else if (vLen == 15) {
                newLen = '3岁以上'
              }
              if (vLen > 13 && v0 < 14 && v0 != 1) {
                return `${new0}个月-${newLen}`
              } else {
                return `${new0}-${newLen}`
              }
            }
          })
        }
      },
      //格式处理
      format (row, column, cellValue) {
        return cellValue.join('、')
      },
      handleSizeChange (val) {
        this.selectLabelData.pageSize = val
        this.getLabelList(val, this.selectLabelData.pageNum)
      },
      handleCurrentChange (val) {
        this.selectLabelData.pageNum = val
        this.getLabelList(this.selectLabelData.pageSize, val)
      },
    }
  }
</script>

<style scoped lang='less'>
  .goods-reading {
    border-bottom: 1px dashed rgb(227, 231, 237);
    margin-bottom: 20px;

    h4 {
      padding: 10px 40px 20px;
    }

    .mark {
      color: #999999;
      font-size: 12px;

      span {
        color: #409EFF;
        font-size: 16px;
        font-weight: 500;
        margin-right: 10px;
      }
    }

    .goods-img {
      min-width: 150px;
      height: 150px;
      border: 1px dashed #dcdfe6;
      display: inline-block;

      img {
        display: block;
        height: 100%;
        margin: 0 auto;
      }
    }

    .upload-btn {
      display: flex;
      justify-content: flex-start;
    }

    .gravidity-weeks {
      background-color: #fff;
      padding-left: 30px;
      border-radius: 4px;
      margin-top: 15px;
      padding-bottom: 10px;
      border: 1px dashed rgb(227, 231, 237);

      &.baby-weeks {
        .el-checkbox {
          width: 95px;
        }
      }

      .el-checkbox {
        width: 53px;
      }

      .selected-weeks {
        color: #67c23a;
      }

    }

    .editor-container {
      position: relative;
      width: 60%;
      min-width: 660px;

      .el-button {
        position: absolute;
        right: 10px;
        top: 12px;
      }
    }

    .goods-reading-label {
      color: #606266;
    }
  }

  .dialog-footer {
    text-align: center;
    padding-bottom: 20px;
  }

  .preview-dialog {
    .preview-container {
      overflow-x: hidden;
      overflow-y: scroll;
      height: 600px;
      width: 375px;
      margin: -15px -20px;
      padding: 0px 15px;
      box-sizing: border-box;

      img {
        display: block;
        width: 100%;
      }
    }
  }

  .search-label {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .editor-look {
    border: 1px solid #ccc;
    width: 60%;

    .editor-look-nav {
      padding-right: 10px;
      height: 50px;
      background: rgb(241, 241, 241);
      display: flex;
      align-items: center;
      justify-content: flex-end;
      border-bottom: 1px solid #ccc;
    }

    .editor-look-content {
      height: 250px;
      overflow-x: hidden;
      overflow-y: auto;
      padding: 0 10px;
    }
  }
</style>
<style>
  .el-tag {
    margin-right: 10px;
  }

  .goods-reading .w-e-text-container {
    height: 250px !important;
  }

  .preview-dialog .el-dialog {
    border-radius: 30px;
    overflow: hidden;
  }

  .rich-text-details {
    line-height: 2;
    letter-spacing: 0.6px;
  }
</style>
